package com.live.shop.home.prologue;

import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.aliyun.AliyunTtsUtil;
import com.live.shop.model.PrologueModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.PrologueListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.TtsMessageEvent;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Calendar;
import java.util.Locale;

public class BatchProloguesActivity extends BaseActivity {
    ImageButton batch_prologue_back;
    EditText batch_prologue_edittext;
    TextView batch_prologue_save;
    String fileDir="";
    UserModel userModel;
    PrologueListDatabase proDb;
    int taskNum = 0;
    int SuccessNum = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_prologues);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        //首先要在你要接受EventBus的界面注册，这一步很重要
        EventBus.getDefault().register(this);

        batch_prologue_back = findViewById(R.id.batch_prologue_back);
        batch_prologue_edittext = findViewById(R.id.batch_prologue_edittext);
        batch_prologue_save = findViewById(R.id.batch_prologue_save);

        batch_prologue_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        batch_prologue_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createAudio();
            }
        });
        fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+"/zhiboMusic";
        File folder = new File(fileDir);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                // 文件夹创建失败
                ToastUtils.Setinfo(getApplicationContext(),"无法创建文件夹！",2);
            }
        }
        UserDatabase userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        proDb = new PrologueListDatabase(getApplicationContext());
    }
    public void createAudio(){//每段str
        try {
            String edit = batch_prologue_edittext.getText().toString();
            if(edit.isEmpty()){
                ToastBottomUtils.Setinfo(getApplicationContext(),"内容不能为空！");
                return;
            }
            ToastBottomUtils.Setinfo(getApplicationContext(),"合成中，请稍后...");
            batch_prologue_save.setClickable(false);

            String[] infos = edit.split("\n");
            for (String str:infos) {
                if(str.replace(" ","").isEmpty()) continue;
                //文件路径
                String outputFile = fileDir+"/ai_"+ DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
                AutoAliyun(str.replace(" ",""),outputFile);
                PrologueModel prologueModel = new PrologueModel(str.replace(" ",""),2,2,outputFile);
                proDb.insertData(prologueModel);
                taskNum ++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void AutoAliyun(String answer,String outputFile){
        if(userModel.getAliyunAccessKeyID().isEmpty() || userModel.getAliyunAppkey().isEmpty() || userModel.getAliyunAccessKeySecret().isEmpty()){
            ToastBottomUtils.Setinfo(getApplicationContext(),"请先配置阿里云密钥！");
            return;
        }
        if(userModel.getAliyunVoiceSelect().isEmpty() || userModel.getAliyunFontName().isEmpty()){
            ToastBottomUtils.Setinfo(getApplicationContext(),"请选择保存阿里云音色！");
            return;
        }
        //实例化tts
        if(GetUtil.getUtf8CharsNum(answer) > 300){
            ToastUtils.Setinfo(getApplicationContext(),"文本长度大于300字符",2);
            return ;
        }
        //语音合成
        AliyunTtsUtil ttsUtil = new AliyunTtsUtil(userModel.getAliyunAppkey(),userModel.getAliyunAccessKeyID(),userModel.getAliyunAccessKeySecret());
        //文本、保存文件名
        ttsUtil.postRequest(getApplicationContext(),answer,outputFile);
    }

    //任意写一个方法，给这个方法一个@Subscribe注解，参数类型可以自定义，但是一定要与你发出的类型相同
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(TtsMessageEvent ttsMessageEvent){
        switch (ttsMessageEvent.getNumber()) {
            case 1://合成成功
                SuccessNum++;
                if(SuccessNum == taskNum){
                    ToastUtils.Setinfo(getApplicationContext(),"已全部合成完毕！",1);
                    GetUtil.getVibrator(getApplicationContext());
                    finish();
                }
                break;
            case 3://异常
                ToastBottomUtils.Setinfo(this,ttsMessageEvent.getMessage());
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
    }
}